package com.minyifang.wcspf.work.ui.home.fragments.home2sub;


import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpFragment;
import com.minyifang.wcspf.common.config.user.UserManager;
import com.minyifang.wcspf.common.utils.AnimUtils;
import com.minyifang.wcspf.common.utils.ArrayUtil;
import com.minyifang.wcspf.common.utils.ImageUtils;
import com.minyifang.wcspf.common.utils.LogUtil;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.work.event.RefreshEvent;
import com.minyifang.wcspf.work.model.HttpRespond;
import com.minyifang.wcspf.work.ui.Global;
import com.minyifang.wcspf.work.ui.goods.activities.GoodsDetailsActivity;
import com.minyifang.wcspf.work.ui.home.activities.MainActivity;
import com.minyifang.wcspf.work.ui.home.model.AddToCarBean;
import com.minyifang.wcspf.work.ui.home.model.ClassBean;
import com.minyifang.wcspf.work.ui.home.model.GoodsBean2;
import com.minyifang.wcspf.work.ui.home.presenter.GoodsListPresenter;
import com.minyifang.wcspf.work.ui.home.view.GoodsListView;
import com.minyifang.wcspf.work.ui.widgets.LineLoadingView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品列表
 */
public class GoodsListFragment extends BaseMvpFragment<GoodsListView, GoodsListPresenter> implements GoodsListView, PopupWindow.OnDismissListener {

    @BindView(R.id.rv_goods_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_choose_class)
    LinearLayout mLlChooseClass;
    @BindView(R.id.v_mask)
    View mViewMask;
    @BindView(R.id.sr_refresh)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_filter_num)
    TextView mTvFilterNum;
    @BindView(R.id.lv_view)
    LineLoadingView mLoadingView;

    private ClassBean.SubClassBean mSubClassBean;
    private SpecialSaleAdapter mSpecialSaleAdapter;
    LinearLayoutManager mLinearLayoutManager;
    private boolean isLoginState;

    private ImageView mClickItemView;
    private ImageView mEndView;
    private AnimUtils mAnimUtils;
    private boolean mShowAnim;

    PopupWindow mPwFilter;
    List<String> mFilterStringList = new ArrayList<>();
    FilterAdapter mFilterAdapter;

    int mOperatedGoodsPosition = -1;
    int mPage = 0;

    String mPrefix = "";
    String mFilter = "";

    List<GoodsBean2> mGoodsBeanList;
    public List<ClassBean.SubClassBean.FilterClassBean> mFilterClassBeanList;

    {
        mGoodsBeanList = new ArrayList<>();
        mFilterClassBeanList = new ArrayList<>();
    }

    public GoodsListFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (getContext() instanceof MainActivity) {
            MainActivity mainActivity = (MainActivity) getContext();
            mEndView = mainActivity.findViewById(R.id.iv_car);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAnimUtils = new AnimUtils(getContext());
        isLoginState = UserManager.getInstance().isLogin();
    }

    @Override
    protected GoodsListPresenter createPresenter() {
        return new GoodsListPresenter();
    }

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_goods_list;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initView() {
        mSpecialSaleAdapter = new SpecialSaleAdapter();
        mRecyclerView.setAdapter(mSpecialSaleAdapter);
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
    }

    @Override
    protected void initData() {
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            getData(false);
        }).setOnLoadMoreListener(refreshLayout -> getData(true));
    }

    @Override
    protected void lazyLoadData() {
    }

    @OnClick(R.id.ll_choose_class)
    void ll_choose_class() {
        if (mPwFilter == null) {
            mFilterAdapter = new FilterAdapter(mFilterStringList, getContext());
            mPwFilter = generateChooseFilterPopupWindow();
        }
        mPwFilter.showAsDropDown(mLlChooseClass);
        showMask();
    }

    public void updateFilterAndGoodsData(ClassBean.SubClassBean subClassBean) {
        mFilterClassBeanList.clear();
        mSubClassBean = subClassBean;
        mPrefix = String.format("%s,%s", mSubClassBean.pid, mSubClassBean.id);
        mFilter = "";
        mFilterClassBeanList.addAll(mSubClassBean.filterClassBeans);
        mFilterStringList.clear();
        LogUtil.e("分类拼接前缀", mPrefix);
        LogUtil.e("过滤字符串", mFilter);
        mFilterStringList.addAll(ArrayUtil.listConvertToStringList(mFilterClassBeanList, filterClassBean -> filterClassBean.name));
        if (mFilterAdapter != null)
            mFilterAdapter.reset();
        mTvFilterNum.setText(String.format("(%s)", mFilterClassBeanList.size()));
        getData(false);
    }

    private PopupWindow generateChooseFilterPopupWindow() {
        View layout = getLayoutInflater().inflate(R.layout.layout_popup_window_choose_class, null);
        PopupWindow popupWindow = new PopupWindow(layout, mLlChooseClass.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        RecyclerView recyclerView = layout.findViewById(R.id.rv_choose_class);
        recyclerView.setAdapter(mFilterAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.PopupWindowAnimStyle);
        popupWindow.setOnDismissListener(this);
        return popupWindow;
    }

    private void showMask() {
        mViewMask.animate().alpha(1f).setDuration(150).start();
    }

    @Override
    public void onDismiss() {
        mViewMask.animate().alpha(0f).setDuration(150).start();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isLoginState != UserManager.getInstance().isLogin()) {
            isLoginState = UserManager.getInstance().isLogin();
            getData(false);
        }
    }

    private void getData(boolean isLoadMore) {
        if (isLoadMore) {
            mPage++;
        } else {
            mPage = 0;
            mGoodsBeanList.clear();
            mSpecialSaleAdapter.notifyDataSetChanged();
        }
        LogUtil.e("prefix:" + mPrefix);
        LogUtil.e("filter:" + mFilter);
        LogUtil.e("result:" + mPrefix + mFilter);
        getPresenter().getGoodsList(mPrefix + "," + mFilter, mPage);
    }


    @Override
    public void showLoadingView() {
        mLoadingView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoadingView() {
        mLoadingView.setVisibility(View.GONE);
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
        mRefreshLayout.finishRefresh().finishLoadMore();
    }

    @Override
    public void onGetListSucceed(List<GoodsBean2> goodsBeanList) {
        mRefreshLayout.finishRefresh().finishLoadMore();
        if (mPage == 0)
            mRecyclerView.scrollToPosition(0);
        mGoodsBeanList.addAll(goodsBeanList);
        mSpecialSaleAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCollectionResult(String message) {
        ToastHelper.getInstance(getContext()).showWarn(message);
        if (mOperatedGoodsPosition < 0)
            return;
        GoodsBean2 goodsBean = mGoodsBeanList.get(mOperatedGoodsPosition);
        int isCollection = goodsBean.getIsCollection();
        goodsBean.setIsCollection(Math.abs(isCollection - 1));
        mSpecialSaleAdapter.notifyItemChanged(mOperatedGoodsPosition);
        mOperatedGoodsPosition = -1;
    }

    @Override
    public void onRequestFailed(String message) {
        ToastHelper.getInstance(getContext()).showWarn(message);
    }

    @Override
    public void showAddToCarRes(HttpRespond<AddToCarBean> respond) {
        sendToUpdateCarNum();
        if (respond.result == 1) {
            //修改数量
            mGoodsBeanList.get(fatherPos).getSkuList().get(childPos).setNum(Integer.parseInt(respond.data.getQuantity()));
            mSpecificationAdapter.notifyItemChanged(childPos);

            if (mShowAnim)
                mAnimUtils.startAnim(mClickItemView, mEndView);
        } else
            ToastHelper.getInstance(getContext()).showWarn(respond.message);
    }

    /**
     * 发送广播通知刷新购物车数量
     */
    private void sendToUpdateCarNum() {
        EventBus.getDefault().post(new RefreshEvent());
    }

    private SpecificationAdapter mSpecificationAdapter;
    private int childPos;
    private int fatherPos;

    public void refreshGoodsList() {
        getData(false);
    }

    class SpecialSaleAdapter extends RecyclerView.Adapter<SpecialSaleAdapter.Holder> {
        @NonNull
        @Override
        public SpecialSaleAdapter.Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_class_goods_list, parent, false));
            holder.itemView.setOnClickListener(v -> GoodsDetailsActivity.start(getActivity(), mGoodsBeanList.get(holder.getAdapterPosition()).getID()));
            holder.ivCollect.setOnClickListener(v -> {
                if (Global.checkLogin(getActivity())) {
                    mOperatedGoodsPosition = holder.getAdapterPosition();
                    GoodsBean2 goodsBean = mGoodsBeanList.get(holder.getAdapterPosition());
                    getPresenter().collectionGoods(goodsBean.getID(), Math.abs(goodsBean.getIsCollection() - 1));
                }
            });
            holder.ivAddCart.setOnClickListener(v -> {
                GoodsBean2 goods = mGoodsBeanList.get(holder.getAdapterPosition());
                if (Global.checkLogin(getContext())) {
                    goods.isOpen = !goods.isOpen;
                    holder.mRvSpecification.setVisibility(goods.isOpen ? View.VISIBLE : View.GONE);
                    new Handler().postDelayed(() -> {
                        if (mLinearLayoutManager.findLastVisibleItemPosition() == holder.getAdapterPosition()
                                && holder.mRvSpecification.getVisibility() == View.VISIBLE) {
                            mRecyclerView.smoothScrollBy(0, holder.mRvSpecification.getHeight());
                        }
                    }, 40);
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull SpecialSaleAdapter.Holder holder, int position) {
            GoodsBean2 goods = mGoodsBeanList.get(position);
//            Glide.with(getActivity()).load(goods.getDeputyPic()).into(holder.ivCover);
            ImageUtils.getInstance().showImage(goods.getDeputyPic(), holder.ivCover);
            holder.tvTitle.setText(goods.getName());
            holder.tvDesc.setText(goods.getDes());
            holder.tvOriginMoney.setText(String.format("￥%s元", goods.getMarketPrice()));
            holder.tvOriginMoney.setPaintFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            holder.tvPrice.setText(String.format("￥%s元", goods.getUnitPrice()));
            holder.tvUnit.setText(String.format("/%s", goods.getPriceName()));
            //是否为新品
            if (goods.getIsNew() == 1) {
                holder.flIsNew.setVisibility(View.VISIBLE);
            } else {
                holder.flIsNew.setVisibility(View.GONE);
            }
            holder.ivCollect.setImageResource(goods.getIsCollection() == 1 ? R.mipmap.ic_goods_collected : R.mipmap.ic_goods_collect);

            holder.mRvSpecification.setVisibility(goods.isOpen ? View.VISIBLE : View.GONE);

//            holder.mRvSpecification.setLayoutManager(new LinearLayoutManager(getContext()));
//            mSpecificationAdapter = new SpecificationAdapter(goods.getSkuList(), holder);
//            holder.mRvSpecification.setAdapter(mSpecificationAdapter);

            holder.setSkuListData(goods.getSkuList());

        }

        @Override
        public int getItemCount() {
            return mGoodsBeanList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            private final List<GoodsBean2.SkuListBean> mSkuList;
            private final SpecificationAdapter mSpecificationAdapter;
            @BindView(R.id.fl_is_new)
            FrameLayout flIsNew;
            @BindView(R.id.tv_title)
            TextView tvTitle;
            @BindView(R.id.tv_desc)
            TextView tvDesc;
            @BindView(R.id.tv_price)
            TextView tvPrice;
            @BindView(R.id.tv_origin_money)
            TextView tvOriginMoney;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.iv_cover)
            ImageView ivCover;
            @BindView(R.id.iv_add_cart)
            ImageView ivAddCart;
            @BindView(R.id.iv_collect)
            ImageView ivCollect;

            @BindView(R.id.mRvSpecification)
            RecyclerView mRvSpecification;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                mRvSpecification.setLayoutManager(new LinearLayoutManager(getContext()));
                mSkuList = new ArrayList<>();
                mSpecificationAdapter = new SpecificationAdapter(mSkuList, this);
                GoodsListFragment.this.mSpecificationAdapter = mSpecificationAdapter;
                mRvSpecification.setAdapter(GoodsListFragment.this.mSpecificationAdapter);
            }

            public void setSkuListData(List<GoodsBean2.SkuListBean> skuList) {
                mSkuList.clear();
                if (skuList != null)
                    mSkuList.addAll(skuList);
                mSpecificationAdapter.notifyDataSetChanged();
            }
        }
    }

    public class FilterAdapter extends RecyclerView.Adapter<FilterAdapter.Holder> {

        private List<String> mStringList;
        private Context mContext;
        private int mDefaultColor = Color.GRAY;
        private int mChoseColor;
        private int mCurChosePosition = -1;

        public FilterAdapter(List<String> stringList, Context context) {
            mStringList = stringList;
            mContext = context;
            mChoseColor = ContextCompat.getColor(context, R.color.colorPrimary);
        }

        public void reset() {
            mCurChosePosition = -1;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View layout = LayoutInflater.from(mContext).inflate(R.layout.item_single_choose2, parent, false);
            return new Holder(layout);
        }

        @Override
        public void onBindViewHolder(@NonNull final Holder holder, final int position) {
            if (mCurChosePosition == position) {
                holder.mTvTitle.setTextColor(mChoseColor);
                holder.mTvTitle.setBackgroundResource(R.drawable.bg_class_choose_item_selected);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    holder.mTvTitle.setElevation(3);
                }
            } else {
                holder.mTvTitle.setTextColor(mDefaultColor);
                holder.mTvTitle.setBackgroundResource(R.drawable.bg_class_choose_item);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    holder.mTvTitle.setElevation(0);
                }
            }
            holder.mTvTitle.setText(mStringList.get(position));
            holder.itemView.setOnClickListener(v -> {
                mCurChosePosition = holder.getAdapterPosition();
                notifyDataSetChanged();
                mFilter = mFilterClassBeanList.get(mCurChosePosition).id;
                getData(false);
                mPwFilter.dismiss();
            });
        }

        @Override
        public int getItemCount() {
            return mStringList.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView mTvTitle;

            Holder(View itemView) {
                super(itemView);
                mTvTitle = itemView.findViewById(R.id.tv_title);
            }
        }
    }

    public class SpecificationAdapter extends RecyclerView.Adapter<SpecificationAdapter.Holder> {

        private List<GoodsBean2.SkuListBean> skuList;
        private SpecialSaleAdapter.Holder mHolder;

        public SpecificationAdapter(List<GoodsBean2.SkuListBean> skuList, SpecialSaleAdapter.Holder holder) {
            this.skuList = skuList;
            this.mHolder = holder;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(LayoutInflater.from(getContext()).inflate(R.layout.item_add_to_cart_category, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            GoodsBean2.SkuListBean bean = skuList.get(position);
            holder.item_price.setText(String.format("￥%s", bean.getPrice()));
            holder.item_specification.setText(String.format("/(%s%s/%s)", bean.getQuantity(), bean.getComSp(), bean.getSkuSp()));
            holder.item_unit_price.setText(String.format("每%s￥%s元", bean.getComSp(), bean.getUnitPrice()));
            holder.edt_num.setText(bean.getNum() + "");

            holder.edt_num.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() == 0) {
                        holder.edt_num.setText("0");
                        holder.edt_num.setSelection(0,1);
                    }
                }
            });

            holder.edt_num.setOnFocusChangeListener((v, hasFocus) -> {
                LogUtil.e(position + "," + bean.getSkuId() + "," + hasFocus);
                if (!hasFocus) {
                    fatherPos = mHolder.getAdapterPosition();
                    childPos = position;
                    getPresenter().addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                    mClickItemView = mHolder.ivCover;
                    mShowAnim = true;
                }
            });

            holder.itemView.setOnClickListener(v -> holder.itemView.setFocusable(true));

            holder.plus.setOnClickListener(v -> {
                fatherPos = mHolder.getAdapterPosition();
                childPos = position;
                LogUtil.e("加--" + fatherPos + "," + childPos);
                holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) + 1 + "");
                getPresenter().addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                mClickItemView = mHolder.ivCover;
                mShowAnim = true;
            });

            holder.reduce.setOnClickListener(v -> {
                fatherPos = mHolder.getAdapterPosition();
                childPos = position;
                LogUtil.e("减--" + fatherPos + "," + childPos);
                holder.edt_num.setText(Integer.parseInt(holder.edt_num.getText().toString()) - 1 < 0 ? "0" : Integer.parseInt(holder.edt_num.getText().toString()) - 1 + "");
                getPresenter().addToCar(bean.getSkuId(), holder.edt_num.getText().toString());
                mShowAnim = false;
            });
        }

        @Override
        public int getItemCount() {
            return skuList == null ? 0 : skuList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.item_price)
            TextView item_price;
            @BindView(R.id.item_specification)
            TextView item_specification;
            @BindView(R.id.item_unit_price)
            TextView item_unit_price;
            @BindView(R.id.iv_plus)
            ImageView plus;
            @BindView(R.id.iv_reduce)
            ImageView reduce;
            @BindView(R.id.tv_num)
            EditText edt_num;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
